package cn.yr.clock.handler;


import cn.hutool.core.util.StrUtil;
import cn.yr.clock.domain.entity.Record;
import cn.yr.clock.domain.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailHandler {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private CacheUserHandler cacheUserHandler;

    public void recordSendEmail(Record record) {
        User user = cacheUserHandler.getUser(record.getClockUser());
        String userName = user.getUserName();
        String object = "打卡通知：" + userName;
        String content = "<div>\n" +
                "\t\t\t<h3>打卡人：{}</h3>\n" +
                "\t\t\t<h3>打卡时间：{}</h3>\n" +
                "\t\t\t<h3>打卡说明：{}</h3>\n" +
                "\t\t\t<h3>打卡截图：<img src=\'{}\' width=\"200px\"/></h3>\n" +
                "\t\t</div>";
        content = StrUtil.format(content, userName, record.getClockTime(), record.getNote(), record.getImg());
        String to = "1102076808@qq.com";
        sendMail(object,content,to);
    }

    public void sendMail(String subject, String content, String... to) {
        String from = "18374976936@163.com";
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message);
        try {
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }
}
